/**
 * Copyright @ 2023 iAuto (Shanghai) Co., Ltd.
 * All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are NOT permitted except as agreed by
 * iAuto (Shanghai) Co., Ltd.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 */

// import {SearchOutlined} from '@ant-design/icons';
import { Col, Form, Image, Input, Modal, Pagination, Row, Select, Space, Divider } from 'antd';
import styles from './index.less';
import { router } from 'umi';
import React, { useEffect, useState } from 'react';
import { useReactive, usePagination, useRequest } from 'ahooks';
import IAutoPage from '@/components/soa/IAutoPage';
import IAutoSearch from '@/components/soa/IAutoSearch';
import IAutoButton from '@/components/soa/IAutoButton';
import { getScenesList, getSeriesModelList } from '@/services/soa/sceneOfficial';
import { connect } from 'dva';

const { Option } = Select;
const { Item, useForm } = Form;

const Index = (props: any) => {
  const {
    location: { pathname },
  } = props;
  const [form] = useForm();
  // true 显示未创建 false 显示没搜索到
  const [showEmpty, setShowEmpty] = useState(true);
  const [options, setOptions] = useState([]);
  const state = useReactive<{
    cnName: string;
    deployStatus: any;
    seriesCode: string;
    modelCode: string;
  }>({
    cnName: '',
    deployStatus: 0,
    seriesCode: '',
    modelCode: '',
  });

  const [isModalOpen, setIsModalOpen] = useState(false);
  const {
    data,
    loading: requestLoading,
    pagination,
    run,
  } = usePagination(
    async ({ current }) => {
      return getScenesList({
        current,
        pageSize: 12,
        name: state.cnName || undefined,
        deployStatus: state.deployStatus || undefined,
        seriesCode: state.seriesCode || undefined,
        modelCode: state.modelCode || undefined,
      });
    },
    {
      defaultPageSize: 12,
      cacheKey: 'vehicleScenesList',
      onSuccess: response => {
        if (pagination?.current === 1 && response.list.length === 0) {
          setShowEmpty(!state.cnName && state.deployStatus === 0);
        }
        if (pagination?.current !== 1 && response.list.length === 0) {
          run({ ...pagination, ...state, current: 1 });
        }
      },
    },
  );
  // 车系车型
  const seriesModelList = useRequest(getSeriesModelList);
  const handleCancel = () => {
    setIsModalOpen(false);
    form.resetFields();
  };

  /**
   * @description 去明细
   * @param id
   */
  const toDetail = (id: string) => {
    router.push('/soaManage/scene/official/detail?sceneUuid=' + id);
  };

  /**
   * @description 去编排
   * @param values
   */
  const toEdit = (values: any) => {
    window.location.href = `/#/soaManage/scene-editing?sceneUuid=${values?.sceneUuid}&cnName=${values?.name}&seriesCode=${values?.seriesCode}&modelCode=${values.modelCode}`;
  };

  /**
   * @description 背景图
   * @param url
   */
  const setBackgroundImage = (url: string) => {
    return {
      background: `url('${url}')`,
      backgroundRepeat: 'round',
    };
  };

  /**
   * @description 渲染卡片
   * @param item
   * @returns 组件
   */
  const renderCard = (item: any) => {
    return (
      <div className={styles.card} style={setBackgroundImage(item.backgroundPicUrl)}>
        <Row>
          <Col span={18}>
            <Row align={'middle'}>
              <Col span={6}>
                <Image className={styles.image} src={item.iconUrl} preview={false} />
              </Col>
              <Col span={18} className={styles.ellipsis}>
                <span className={styles.appName} onClick={() => toDetail(item?.sceneUuid)}>
                  {item.name}
                </span>
              </Col>
            </Row>
          </Col>
          {item.deployStatus === 1 && (
            <Col span={6}>
              <Row justify={'end'}>
                <Col>
                  <div className={styles.putOn}>
                    <span className={styles.putOnText}>已上架</span>
                  </div>
                </Col>
              </Row>
            </Col>
          )}
        </Row>
        {item.description ? (
          <Row>
            <Col span={24}>
              <Row>
                <Col span={5}></Col>
                <Col span={19} className={styles.description1}>
                  <span className={styles.description}> {item.description}</span>
                </Col>
              </Row>
            </Col>
          </Row>
        ) : (
          <Row style={{ height: 22 }}></Row>
        )}
        <Row justify={'end'}>
          <Col>
            <Space className={styles.bottom}>
              <IAutoButton
                onClick={() => toEdit(item)}
                pathname={pathname}
                auth={'official_doEdit'}
              >
                编排
              </IAutoButton>

              <IAutoButton
                onClick={() => toDetail(item?.sceneUuid)}
                pathname={pathname}
                auth={'official_doDetail'}
              >
                详情
              </IAutoButton>
            </Space>
          </Col>
        </Row>
      </div>
    );
  };

  /**
   * @description 搜索
   * @returns
   */
  const onSearch = () => {
    run({ ...pagination, ...state, current: 1 });
  };

  /**
   * @description 弹窗
   */
  const showModal = () => {
    seriesModelList.run();
    setIsModalOpen(true);
  };

  /**
   * @description 跳转
   * @param values
   */
  const onSave = (values: any) => {
    window.location.href = `/#/soaManage/scene-editing?seriesCode=${
      values?.seriesModel1
    }&modelCode=${values?.seriesModel2.join(',')}`;
  };

  const onChangeSelect = (value: any) => {
    state.deployStatus = value;
    onSearch();
  };

  const onChangeModelCodeSelect = (value: any) => {
    state.modelCode = value;
  };

  /**
   * @description 车系选择
   * @param value
   */
  const handleProvinceChange = (value: any) => {
    form.setFieldsValue({
      seriesModel2: [],
    });
    for (const obj of seriesModelList?.data?.data || []) {
      if (value === obj?.code) {
        setOptions(obj.children);
      }
    }
  };

  /**
   * @description 车系选择
   * @param value
   */
  const handleSeriesCodeChange = (value: any) => {
    state.seriesCode = value;
    form.setFieldsValue({
      seriesModel2: [],
    });
    for (const obj of seriesModelList?.data?.data || []) {
      if (value === obj?.code) {
        setOptions(obj.children);
      }
    }
  };

  useEffect(() => {
    if (isModalOpen) {
      props.dispatch({
        type: 'vehicleInfoQuery/getData',
        payload: {
          url: '/common/vehicle/getcurrentbrand',
        },
        callback: (e: any) => {
          form.setFieldsValue({ brand: e?.data?.[0]?.brandName });
        },
      });
    }
  }, [isModalOpen]);

  const allSelected = () => {
    form.setFieldsValue({
      seriesModel2: options.map((item: any) => item.code),
    });
  };

  const clearAll = () => {
    form.setFieldsValue({
      seriesModel2: [],
    });
  };

  return (
    <div className={styles.main}>
      <IAutoSearch>
        <Row gutter={[8, 8]}>
          <Col md={6} sm={12}>
            <Input
              className={`${styles.radius} ${styles.width}`}
              // suffix={<SearchOutlined onClick={onSearch} />}
              allowClear
              placeholder={'请输入场景名称搜索'}
              maxLength={20}
              value={state.cnName}
              onChange={e => (state.cnName = e.target.value)}
              // onPressEnter={onSearch}
            />
          </Col>
          <Col md={6} sm={12} style={{ display: 'flex', alignItems: 'center' }}>
            <span style={{ width: '100px' }}>场景状态:</span>
            <Select
              className={`${styles.width}`}
              allowClear
              value={state.deployStatus as any}
              onChange={onChangeSelect}
            >
              <Option value={0}>全部</Option>
              <Option value={1}>已上架</Option>
            </Select>
          </Col>

          <Col md={6} sm={12} style={{ display: 'flex', alignItems: 'center' }}>
            <span style={{ width: '60px' }}>车系:</span>
            <Select
              style={{ width: '100%' }}
              className={styles.itemWidth}
              placeholder={'请选择车系'}
              value={state.seriesCode as string}
              onChange={handleSeriesCodeChange}
              allowClear
            >
              {seriesModelList?.data?.data?.map?.((obj: any) => (
                <Option value={obj.code} key={obj.code}>
                  {obj.name}
                </Option>
              ))}
            </Select>
          </Col>

          <Col md={6} sm={12} style={{ display: 'flex', alignItems: 'center' }}>
            <span style={{ width: '60px' }}>车型:</span>
            <Select
              style={{ width: '100%' }}
              className={styles.itemWidth}
              showArrow
              placeholder={'请选择车型'}
              value={state.modelCode as string}
              onChange={onChangeModelCodeSelect}
              // mode={'multiple'}
              allowClear
            >
              {options.map?.((obj: any) => (
                <Option value={obj.code} key={obj.code}>
                  {obj.name}
                </Option>
              ))}
            </Select>
          </Col>
          <Col span={24}>
            <Row justify={'end'}>
              <Col>
                <Space>
                  {/*<Button size={'small'} onClick={() => onSearch()}>*/}
                  {/*  查询*/}
                  {/*</Button>*/}
                  <IAutoButton
                    buttonType={'form'}
                    type={undefined}
                    onClick={() => onSearch()}
                    pathname={pathname}
                    auth={'official_doSearch'}
                  >
                    查询
                  </IAutoButton>
                  <IAutoButton
                    buttonType={'form'}
                    type={'primary'}
                    onClick={() => showModal()}
                    pathname={pathname}
                    auth={'official_doCreate'}
                  >
                    创建场景
                  </IAutoButton>
                </Space>
              </Col>
            </Row>
          </Col>
        </Row>
      </IAutoSearch>
      <IAutoPage loading={requestLoading}>
        {data!?.list?.length > 0 ? (
          <div>
            <Row gutter={24}>
              {data!?.list?.map?.((item: any) => {
                const col = 6;
                return (
                  <Col span={col} key={item.sceneUuid}>
                    {renderCard(item)}
                  </Col>
                );
              })}
            </Row>

            <Row justify="end" className={styles.marginTop}>
              <span>总共{data?.total}个项目</span>
              <Col>
                <Pagination {...pagination} size={'small'} />
              </Col>
            </Row>
          </div>
        ) : (
          <div className={styles.noResult}>
            {showEmpty ? (
              <>
                <div>{/*<Image src={noScene} preview={false} />*/}</div>
                <p>{`您还未创建场景`}</p>
              </>
            ) : (
              <>
                <p>没有搜索到相关场景</p>
              </>
            )}
          </div>
        )}

        <Modal
          title={<span className={styles.modalTitle}>创建场景</span>}
          visible={isModalOpen}
          onCancel={handleCancel}
          okText={'创建'}
          onOk={form.submit}
        >
          <Form form={form} onFinish={onSave} colon={true} labelCol={{ span: 4 }}>
            <Item name="label">
              <span>在编排场景前请选择该场景适用的品牌车系：</span>
            </Item>

            <Item label="适用品牌" name="brand">
              <Input disabled></Input>
            </Item>

            <Item
              label="适用车系"
              name="seriesModel1"
              rules={[
                {
                  required: true,
                  message: '车系信息为必填内容，请选择！',
                },
              ]}
            >
              <Select
                className={styles.itemWidth}
                placeholder={'请选择车系'}
                onChange={handleProvinceChange}
              >
                {seriesModelList?.data?.data?.map?.((obj: any) => (
                  <Option value={obj.code} key={obj.code}>
                    {obj.name}
                  </Option>
                ))}
              </Select>
            </Item>

            <Item
              label="适用车型"
              name="seriesModel2"
              rules={[
                {
                  required: true,
                  message: '车型信息为必填内容，请选择！',
                },
              ]}
            >
              <Select
                mode="multiple"
                className={styles.itemWidth}
                showArrow
                placeholder={'请选择车型'}
                dropdownRender={menu => (
                  <>
                    {menu}
                    <Divider style={{ margin: '8px 0' }} />
                    <div className={styles.extraBtn}>
                      <div className={styles.extraBtnItem} onClick={allSelected}>
                        全部选择
                      </div>
                      <div className={styles.extraBtnItem} onClick={clearAll}>
                        全部取消
                      </div>
                    </div>
                  </>
                )}
              >
                {options.map?.((obj: any) => (
                  <Option value={obj.code} key={obj.code}>
                    {obj.name}
                  </Option>
                ))}
              </Select>
            </Item>
          </Form>
        </Modal>
      </IAutoPage>
    </div>
  );
};

export default connect(({ vehicleInfoQuery }: { vehicleInfoQuery: any }) => ({
  vehicleInfoQuery: vehicleInfoQuery,
}))(Index);
